package com.xxx.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.http.HttpStatus;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.HiddenHttpMethodFilter;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 去除APPLICATION_FORM_URLENCODED请求的警告信息
 *
 * @version 1.0
 * @since 1.0
 */
@Slf4j
@Configuration
public class HttpMethodFilter extends HiddenHttpMethodFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse r,
                                    FilterChain fc) throws ServletException, IOException {
        LocalDateTime startTime = LocalDateTime.now();
        if ((RequestMethod.POST.name().equals(request.getMethod()) || RequestMethod.PUT.name().equals(request.getMethod()))
                && MediaType.APPLICATION_FORM_URLENCODED.equals(request.getContentType())) {
            //Skip this filter and call the next filter in the chain.
            fc.doFilter(request, r);
        } else {
            //Continue with processing this filter.
            super.doFilterInternal(request, r, fc);
        }
        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime, endTime);
        String info = request.getMethod()
                + ">>>>>>"
                + request.getRequestURI()
                + "======>请求耗时: " + duration.toMillis() + " 毫秒，返回状态为：" + r.getStatus();
        if ("favicon.ico".equalsIgnoreCase(request.getRequestURI())) {
            return;
        }
        if (HttpStatus.OK_200 == r.getStatus()) log.info(info);
        else log.error(info);
    }
}
